package cn.oowoo.rabbitmq.simple;

import cn.oowoo.rabbitmq.config.RabbitConfig;
import cn.oowoo.rabbitmq.config.RabbitExchangeTypeEnum;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author ZhangBin
 * @Date 2021/5/8 13:48
 * @Description: 简单消息发送-消费着
 *
 **/
public class SimpleConsumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitConfig.createConnection();
        // 创建消息通道
        Channel channel = connection.createChannel();
        // 声明交换机
        // String exchange, 交换机名称
        // String type, 交换机类型
        // boolean durable,是否持久化到磁盘
        // boolean autoDelete,自动删除，不再使用的时候是否自动删除
        // Map<String, Object> arguments  附加的属性
        channel.exchangeDeclare(RabbitConfig.EXCHANGE_SIMPLE_NAME, RabbitExchangeTypeEnum.DIRECT.getExchangeType(),false, false, null);

        // 声明队列
        // String queue,
        // boolean durable, 是否持久化到磁盘
        // boolean exclusive, 排他性，是否只对当前连接可见
        // boolean autoDelete, 是否自动删除
        // Map<String, Object> arguments
        channel.queueDeclare(RabbitConfig.QUEUE_SIMPLE_NAME, false, false, false, null);

        // 绑定队列和交换机
        channel.queueBind(RabbitConfig.QUEUE_SIMPLE_NAME,RabbitConfig.EXCHANGE_SIMPLE_NAME,RabbitConfig.ROUTING_SIMPLE_KEY);

        // 创建消费者
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "UTF-8");
                System.out.println("Received message : " + msg);
                System.out.println("consumerTag : " + consumerTag );//本次链接会话的名字
                System.out.println("deliveryTag : " + envelope.getDeliveryTag() ); //deliveryTag 每次接收消息+1
                System.out.println("properties.messageid : " + properties.getMessageId());
                System.out.println("properties.timestamp : " + properties.getTimestamp());
                System.out.println("properties.header.token : " + properties.getHeaders().get("token"));

            }
        };

        /**
         * autoAck= false :关闭自动确认，也就是开启手动确认
         * 开始获取消息，注意这里开启了手工应答（关闭自动应答）
         * String basicConsume(String queue, boolean autoAck, Consumer callback)
         *
         */
        channel.basicConsume(RabbitConfig.QUEUE_SIMPLE_NAME, true, consumer);
    }
}
